#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Wave Relay
# Copyright (C) 2010 Yakovlev Vladimir [nvbn.rm@gmail.com]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


from PyQt4 import QtCore, QtGui
from time import sleep
from interface import Ui_MainWindow
import sys
from search import LastSearch
from vk import Vkontakte
import thread
from settings import Ui_Settings
import signal
import pylast
import config
import mediawidgets
import search
import player


class main:
    """Main class"""
    config = None
    settings_widget = None
    widget = None
    playlist = None
    searchlist = None
    vk = None
    lastfm = None
    scrobbler = None
    player = None
    search = None

    def __init__(self, app, widget = Ui_MainWindow(), settings_widget = Ui_Settings()):
        """Init class

        Keyword arguments:
        app -- QApplication
        widget -- Ui_MainWindow
        settings_widget -- Ui_Settings

        Returns: None

        """
        self.app = app
        self.config = config.config(self)
        self.settings_widget = settings_widget
        self.widget = widget
        self.search = search.Search(self)
        self.player = player.Player(self)
        self._init_services()
        self._init_icons()
        self._init_events()
        self._init_menu()
        self.searchlist = mediawidgets.Search(self.widget.searchResult)
        self.playlist = mediawidgets.Playlist(self.widget.playList)

        if self.config.save_playlist in ('True', True):
            try:
                self.playlist.load(self.config.playlist)
            except:
                pass
        print self.config.save_search
        print bool(self.config.save_search)
        if self.config.save_search in ('True', True):
            try:
                self.search.load(self.config.search)
            except:
                pass

    def _init_services(self):
        """Init network services, login to it"""
        if self.config.vk_login == None or self.config.vk_password == None:
            self.config.show_settings()
        self.vk = Vkontakte(self.config.vk_login, self.config.vk_password)
        try:
            self.lastfm = LastSearch(self.config.ls_login, self.config.ls_password)
            self.scrobbler = self.lastfm.network.get_scrobbler('tst', '1.0')
            return(True)
        except pylast.WSError:
            self.lastfm = LastSearch()
            self.config.ls_scrob = False
            self.scrobbler = None
            return(False)

    def _init_icons(self):
        """Init icons"""
        self.widget.icon_pause = QtGui.QIcon()
        self.widget.icon_pause.addPixmap(QtGui.QPixmap("media-playback-pause.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.widget.icon_play = QtGui.QIcon()
        self.widget.icon_play.addPixmap(QtGui.QPixmap("media-playback-start.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.widget.icon_noplay = QtGui.QIcon()
        self.widget.icon_noplay.addPixmap(QtGui.QPixmap("spacer.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.widget.icon_max_volume = QtGui.QIcon()
        self.widget.icon_max_volume.addPixmap(QtGui.QPixmap("audio-volume-high.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.widget.icon_med_volume = QtGui.QIcon()
        self.widget.icon_med_volume.addPixmap(QtGui.QPixmap("audio-volume-medium.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.widget.icon_min_volume = QtGui.QIcon()
        self.widget.icon_min_volume.addPixmap(QtGui.QPixmap("audio-volume-low.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.widget.icon_mute_volume = QtGui.QIcon()
        self.widget.icon_mute_volume.addPixmap(QtGui.QPixmap("audio-volume-muted.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

    def _init_events(self):
        """Init slosts and events"""
        QtCore.QObject.connect(self.widget.searchEdit, QtCore.SIGNAL('returnPressed()'), self.search.find)
        QtCore.QObject.connect(self.widget.searchList, QtCore.SIGNAL('clicked()'), self.search.find)
        QtCore.QObject.connect(self.widget.searchResult, QtCore.SIGNAL('itemDoubleClicked(QTreeWidgetItem *, int)'), self.search.click)
        QtCore.QObject.connect(self.widget.playList, QtCore.SIGNAL('itemDoubleClicked(QTreeWidgetItem *, int)'), self.player.play_threaded)
        QtCore.QObject.connect(self.widget.next, QtCore.SIGNAL('clicked()'), self.player.next)
        QtCore.QObject.connect(self.widget.prev, QtCore.SIGNAL('clicked()'), self.player.prev)
        QtCore.QObject.connect(self.widget.play, QtCore.SIGNAL('clicked()'), self.player.play_button)
        QtCore.QObject.connect(self.widget.backList, QtCore.SIGNAL('clicked()'), self.search.back_history)
        QtCore.QObject.connect(self.widget.actionAll, QtCore.SIGNAL('activated()'), self.config.set_repeat)
        QtCore.QObject.connect(self.widget.actionTrack, QtCore.SIGNAL('activated()'), self.config.set_repeat_song)
        QtCore.QObject.connect(self.widget.actionNone, QtCore.SIGNAL('activated()'), self.config.set_no_repeat)
        QtCore.QObject.connect(self.widget.actionLinear, QtCore.SIGNAL('activated()'), self.config.set_linear)
        QtCore.QObject.connect(self.widget.actionShuffle, QtCore.SIGNAL('activated()'), self.config.set_random)
        QtCore.QObject.connect(self.widget.actionConfigure_Accounts, QtCore.SIGNAL('activated()'), self.config.show_settings)
        QtCore.QObject.connect(self.widget.actionOpen_Playlis, QtCore.SIGNAL('activated()'), self.open_dialog)
        QtCore.QObject.connect(self.widget.actionSave_Playlist, QtCore.SIGNAL('activated()'), self.save_dialog)
        QtCore.QObject.connect(self.widget.actionExit_2, QtCore.SIGNAL('activated()'), self.close)
        QtCore.QObject.connect(self.widget.actionRestore_playlist, QtCore.SIGNAL('activated()'), self.config.set_save_playlist)
        QtCore.QObject.connect(self.widget.actionAbout_Qt, QtCore.SIGNAL('activated()'), QtGui.QApplication.aboutQt)
        QtCore.QObject.connect(self.widget.actionRestore_search, QtCore.SIGNAL('activated()'), self.config.set_save_search)
        QtCore.QObject.connect(self.widget.love, QtCore.SIGNAL('clicked()'), self.player.love_button)
        QtCore.QObject.connect(self.app, QtCore.SIGNAL('aboutToQuit()'), self.aboutToQuit)
        self.widget.playList.contextMenuEvent = self.context_menu_playlist
        self.widget.playList.dropEvent = self.on_drop
        self.widget.searchType.insertItem(0, 'Artist')
        self.widget.searchType.insertItem(1, 'Album')
        self.widget.searchType.insertItem(2, 'Song')
        self.widget.searchType.insertItem(3, 'Genre')

    def _init_menu(self):
        """Initiale menu"""
        tobool = lambda element: str(element) == 'True'
        random = tobool(self.config.random)
        repeat = tobool(self.config.repeat)
        repeat_song = tobool(self.config.repeat_song)
        scrob = tobool(self.config.ls_scrob)
        if repeat or repeat_song:
            self.widget.actionNone.setChecked(False)
        else:
            self.widget.actionNone.setChecked(True)
        self.widget.actionTrack.setChecked(repeat_song)
        self.widget.actionAll.setChecked(repeat)
        if random:
            self.widget.actionLinear.setChecked(False)
        else:
            self.widget.actionLinear.setChecked(True)
        self.widget.actionShuffle.setChecked(random)
        self.widget.actionRestore_playlist.setChecked(tobool(self.config.save_playlist))
        self.widget.actionRestore_search.setChecked(tobool(self.config.save_search))

    def context_menu_playlist(self, event):
        """Context menu for playlist

        Keyword arguments:
        event -- QEvent

        Returns: None

        """
        menu = QtGui.QMenu(self.widget.playList)
        deleteAction = menu.addAction("Delete")
        clearAction = menu.addAction("Clear")
        refreshAction = menu.addAction("Try another url")
        if self.config.ls_scrob:
            loveAction = menu.addAction("Love")
        else:
            loveAction = False
        action = menu.exec_(self.widget.playList.mapToGlobal(event.pos()))
        if action == clearAction:
            self.playlist.clear()
        elif action == deleteAction:
            self.playlist.remove(self.player.current_song)
        elif action == loveAction:
            pass
        elif action == refreshAction:
            thread.start_new_thread(lambda song: song.get_url(self.vk, True), (self.playlist.widget.currentItem(), ))
            if self.playlist.widget.currentItem() == self.player.current_song:
                self.player.play_threaded(self.player.current_song)



    def on_drop(self, event):
        """Action for dropping song to playlist

        Keyword arguments:
        event -- QEvent

        Returns: None

        """
        drop = lambda element: thread.start_new_thread(lambda item: self.playlist.append(mediawidgets.Song(item)),(element, ))
        item = event.source().currentItem()
        if self.searchlist.type == 2:
            drop(item.song)
        else:
            for track in item.get_songs():
                drop(track)


    def status(self, status):
        """Set play/stop satus

        Keyword arguments:
        status -- Boolean

        Returns: None

        """
        if status:
            self.widget.play.setText('Stop')
            self.widget.play.setIcon(self.widget.icon_pause)
            self.player.current_song.setIcon(0, self.widget.icon_play)
        else:
            self.widget.play.setText('Play')
            self.widget.play.setIcon(self.widget.icon_play)
            while self.player.current_song == None:
                sleep(1)
            self.player.current_song.setIcon(0, self.widget.icon_pause)

    @QtCore.pyqtSlot()
    def open_dialog(self):
        """View dialog for opening playlist"""
        file = unicode(QtGui.QFileDialog.getOpenFileName(None , 'Open file',
                    self.config.home))
        self.playlist.load(file)

    @QtCore.pyqtSlot()
    def save_dialog(self):
        """View dialog for saving playlist"""
        file = unicode(QtGui.QFileDialog.getSaveFileName(None , 'Save file',
                    self.config.home))
        self.playlist.save(file)

    @QtCore.pyqtSlot()
    def aboutToQuit(self):
        """Save playlist and search before quit app"""
        self.playlist.save(self.config.playlist)
        self.search.save_last(self.config.search)

    @QtCore.pyqtSlot()
    def close(self):
        """Close application"""
        sys.exit(0)




signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QtGui.QApplication(sys.argv)
app.setApplicationName('Wave Relay')
MainWindow = QtGui.QMainWindow()
MainWindow.setWindowIcon(QtGui.QIcon('icon.png'))
widget = Ui_MainWindow()
widget.setupUi(MainWindow)
Main = main(app, widget, Ui_Settings())
MainWindow.show()
sys.exit(app.exec_())
